/**
 * Main App Component
 * Requirements: 1.1, 2.1, 5.1
 * 
 * Integrates 3D scene, chat interface, and emotion report display
 */

import { useState } from 'react';
import { Scene3D } from './components/Scene3D';
import { ChatInterface } from './components/ChatInterface';
import { EmotionReport } from './components/EmotionReport';
import { generateInitialSceneObjects } from './utils/sceneUtils';
import { EmotionReport as EmotionReportType } from './types';
import { analyzeEmotion, generateImage } from './services/api';

function App() {
  // Global state for report data
  const [report, setReport] = useState<EmotionReportType | null>(null);
  const [generatedImage, setGeneratedImage] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [sceneObjects] = useState(() => generateInitialSceneObjects());

  // Handle chat submission
  // Requirements: 3.1, 4.1
  const handleChatSubmit = async (text: string) => {
    setIsLoading(true);
    setReport(null);
    setGeneratedImage(null);
    
    try {
      // Call emotion analysis API
      const emotionResponse = await analyzeEmotion(text);
      
      if (!emotionResponse.success) {
        throw new Error(emotionResponse.error || '情绪分析失败');
      }
      
      // Set the emotion report
      setReport(emotionResponse.report);
      
      // Generate image in parallel (don't block on it)
      generateImage(emotionResponse.imagePrompt)
        .then(imageResponse => {
          if (imageResponse.success) {
            setGeneratedImage(imageResponse.imageUrl);
          } else {
            console.error('Image generation failed:', imageResponse.error);
            // Use placeholder on failure (Requirement 4.3)
            setGeneratedImage('https://via.placeholder.com/400x300?text=Image+Generation+Failed');
          }
        })
        .catch(error => {
          console.error('Image generation error:', error);
          // Use placeholder on error (Requirement 4.3)
          setGeneratedImage('https://via.placeholder.com/400x300?text=Image+Generation+Failed');
        });
        
    } catch (error) {
      console.error('Error submitting chat:', error);
      
      // Show error to user
      const errorMessage = (error as Error).message || '发生错误，请重试';
      alert(errorMessage);
      
      // Reset loading state
      setIsLoading(false);
      return;
    }
    
    setIsLoading(false);
  };

  // Handle save report
  const handleSaveReport = () => {
    if (!report) return;
    
    // Create a simple text representation of the report
    const reportText = `
情绪分析报告
时间: ${report.timestamp.toLocaleString()}

情绪分析:
${report.emotions.map(e => `- ${e.name}: ${e.intensity}%`).join('\n')}

建议:
${report.suggestions.map((s, i) => `${i + 1}. ${s}`).join('\n')}

总结:
${report.summary}
    `.trim();
    
    // Create and download as text file
    const blob = new Blob([reportText], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `emotion-report-${Date.now()}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // Handle share report
  const handleShareReport = async () => {
    if (!report) return;
    
    const shareText = `我的情绪分析: ${report.summary}`;
    
    if (navigator.share) {
      try {
        await navigator.share({
          title: '情绪分析报告',
          text: shareText,
          url: window.location.href,
        });
      } catch (error) {
        console.log('Share cancelled or failed:', error);
      }
    } else {
      // Fallback: copy to clipboard
      try {
        await navigator.clipboard.writeText(shareText);
        alert('已复制到剪贴板！');
      } catch (error) {
        console.error('Failed to copy:', error);
      }
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-purple-900 via-blue-900 to-indigo-900 relative overflow-hidden">
      {/* 3D Scene Background - Adjust for mobile devices (Requirement 1.4) */}
      <Scene3D 
        objects={sceneObjects}
        enableParallax={true}
        onLoad={() => console.log('3D Scene loaded')}
      />
      
      {/* Main Content - Responsive layout (Requirement 1.4) */}
      <div className="relative z-10 min-h-screen flex flex-col px-4 sm:px-6 lg:px-8">
        {/* Header - Responsive text sizing */}
        <header className="pt-6 sm:pt-10 pb-4 sm:pb-6">
          <h1 className="text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-bold text-white text-center">
            Emotion Analysis
          </h1>
          <p className="text-sm sm:text-base text-white/70 text-center mt-2">
            分享你的想法，探索你的情绪
          </p>
        </header>
        
        {/* Chat Interface - Responsive spacing */}
        <div className="flex-1 flex flex-col justify-center py-4 sm:py-8">
          <ChatInterface 
            onSubmit={handleChatSubmit}
            isLoading={isLoading}
            placeholder="分享你的想法..."
          />
        </div>
        
        {/* Emotion Report - Responsive spacing */}
        {(report || isLoading) && (
          <div className="pb-6 sm:pb-10">
            <EmotionReport
              report={report}
              generatedImage={generatedImage}
              isLoading={isLoading}
              onSave={handleSaveReport}
              onShare={handleShareReport}
            />
          </div>
        )}
      </div>
    </div>
  );
}

export default App;
